//
//  StrongholdViewController.swift
//  QuantumWar
//
//  Created by mysj on 16/7/25.
//  Copyright © 2016年 zeng. All rights reserved.
//

import UIKit
import Photos

class StrongholdViewController: UIViewController {
    
    @objc private func presentAlert() {
        if #available(iOS 8.0, *) {
            let Alert = UIAlertController(title: "选中图片来源", message: "", preferredStyle: .Alert)
            
            Alert.addAction(UIAlertAction(title: "从相册选取", style: .Default, handler: { (_) in
                self.s_immagePickerController.sourceType = .SavedPhotosAlbum
                self.presentViewController(self.s_immagePickerController, animated: true, completion: nil)
            }))
            
            Alert.addAction(UIAlertAction(title: "拍照", style: .Default, handler: { (_) in
                self.s_immagePickerController.sourceType = .Camera
                self.presentViewController(self.s_immagePickerController, animated: true, completion: nil)
            }))
            
            Alert.addAction(UIAlertAction(title: "取消", style: .Default, handler:nil))
            
            presentViewController(Alert, animated: true, completion: nil)
            
        } else {
            let  alert = UIAlertView(title: "选择图片来源", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "从相册选取", "拍照")
            
            alert.show()
        }
    }
    
    @objc private func cancelDidClick() {
        view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendNewDidClick() {
        view.endEditing(true)
        guard s_nameText != "" && s_describeText != "" else {
            return
        }
        guard s_imgView.image != nil else {
            presentAlert()
            return
        }
        
        let data1 = s_imgView.image?.resetSizeOfImageData(s_imgView.image!, maxSize: 500)
        
        let data2 = UIImageJPEGRepresentation(s_imgView.image!, 0.5)
        
        let data3  = UIImagePNGRepresentation(s_imgView.image!)
        
        print(data2?.length)
//        print((data1?.length)! / 1024 * 1024)
        let len:Double = Double((data2?.length)!) / 1024.0
        
        print(len)
//        print((data3?.length)! / 1024 * 1024)
        
        
        upImg("img.png", data: data2!) { (isSuccess) in
            
            if isSuccess == true  {
                
                print("上传成功")
            } else {
                print("上传失败")
            }
            
        }
        
        
        
        
    }
    
    @objc private func keyboardFrameWillChange(not: NSNotification) {
        let durtion = not.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.floatValue
        let frame = not.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        if CGRectGetMaxY(s_sendNew.frame) < frame.origin.y {
            UIView.animateWithDuration(Double(durtion), animations: {
                self.view.transform = CGAffineTransformIdentity
            })
        } else {
            let y = CGRectGetMaxY(s_sendNew.frame) - frame.origin.y
            UIView.animateWithDuration(Double(durtion), animations: {
                self.view.transform = CGAffineTransformMakeTranslation(0, -y)
            })
        }
    }
    
    private func startLocating() {
        
        s_locService.startUserLocationService()
        s_mapView.showsUserLocation = false
        s_mapView.userTrackingMode = BMKUserTrackingModeFollow
        s_mapView.showsUserLocation = true
    }
    
    
    //MARK: -
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        setUp()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        print( UIDevice.currentDevice().name)
        //        startLocating()
        
        //                generateSuitImages("/Users/mysj/Desktop/IM_Images")
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardFrameWillChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 82 137 177
        s_mapView.viewWillAppear()
        s_mapView.delegate = self
        s_locService.delegate = self
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        s_mapView.viewWillDisappear()
        s_mapView.delegate = nil
        s_locService.delegate = nil
    }
    
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    // MARK: -
    private var s_location           = CLLocationCoordinate2D()
    private var s_nameText           = ""
    
    private var s_describeText       = ""
    
    private lazy var s_titleLabel    = UILabel(text: "新据点", font: 15)
    
    private lazy var s_tpView        = UIView(backColor: RGB(21, g: 63, b: 148))
    
    private lazy var s_imgView       = UIImageView()
    
    private lazy var s_imgViewBack   = UIImageView(imgName: "Stronghold_imageBack")
    
    private lazy var s_imgViewTitle  = UILabel(text: "图片名", font: 12, color: hexString("09e6ff"))
    
    private lazy var s_imgViewBtn    = UIButton(imgName: "Stronghold_btn_0")
    
    private lazy var s_nameLabel     = UILabel(text: "昵称", font: 12, color: hexString("09e6ff"))
    
    private lazy var s_describe      = UILabel(text: "输入描述", font: 12, color: hexString("09e6ff"))
    
    private lazy var s_cancel        = UIButton(title: "取消", color: UIColor.whiteColor())
    
    private lazy var s_sendNew       = UIButton(title: "确定", color: UIColor.whiteColor())
    
    private lazy var s_nameTextView  = UITextView(TextColor: UIColor.whiteColor(),  borderCorlor: RGB(82, g: 137, b: 177))
    
    private lazy var s_describeTextView = UITextView(TextColor: UIColor.whiteColor(), borderCorlor: RGB(82, g: 137, b: 177))
    
    private lazy var s_immagePickerController = UIImagePickerController()
    
    private lazy var s_locService = BMKLocationService()
    
    private lazy var s_mapView: BMKMapView = {
        
        let mp = BMKMapView()
        //        mp.showMapPoi = false
        mp.overlookEnabled = false
        mp.zoomEnabledWithTap = false  //双击
        mp.buildingsEnabled = false     //3D楼的效果
        mp.trafficEnabled = false
        mp.zoomEnabled = false
        mp.showsUserLocation = true
        mp.mapType = UInt(BMKMapTypeSatellite)
        mp.trafficEnabled = false//关闭实时路况图层
        mp.zoomLevel = 16;
        
        return mp
    }()
}


extension StrongholdViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        picker.dismissViewControllerAnimated(true, completion: nil)
        s_imgView.image = info[UIImagePickerControllerEditedImage] as? UIImage
    }
    
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
 // UIImageWriteToSavedPhotosAlbum(img, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) 保存相册
    }
}

extension StrongholdViewController: UIAlertViewDelegate {
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex > 1 {
            self.s_immagePickerController.sourceType = .Camera
        } else {
            self.s_immagePickerController.sourceType = .SavedPhotosAlbum
        }
        self.presentViewController(self.s_immagePickerController, animated: true, completion: nil)
    }
}

extension StrongholdViewController: BMKMapViewDelegate ,BMKLocationServiceDelegate {
    
    func mapViewDidFinishLoading(mapView: BMKMapView!) {
        
        print("地图初始化完毕")
    }
    
    func mapView(mapView: BMKMapView!, onClickedMapBlank coordinate: CLLocationCoordinate2D) {
        s_location = coordinate
    }
    
    /// 定位
    func didUpdateUserHeading(userLocation: BMKUserLocation!) {
        
        if s_location.latitude != 0 {
            s_location = userLocation.location.coordinate
        }
        s_mapView.updateLocationData(userLocation)
    }

    func didFailToLocateUserWithError(error: NSError!) {
        debugPrint("定位 error")
    }
    
}

extension StrongholdViewController: UITextViewDelegate {
    
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        if (text as NSString).isEqualToString("\n") {
            self.view.endEditing(true)
            return false
        }
        return true
    }
    
    func textViewDidChange(textView: UITextView) {
        
    }
    
    func textViewDidEndEditing(textView: UITextView) {
        if (textView == s_nameTextView) && (textView.text.characters.count > 2 && textView.text.characters.count < 18) {
            s_nameText = textView.text
        } else if (textView == s_describeTextView) && (textView.text.characters.count > 2 && textView.text.characters.count < 18) {
            s_describeText = textView.text
        }
    }
}


extension StrongholdViewController {
    
    
    private func setUp() {
        
        let bkv =  UIImageView(image: UIImage(named: "common_bg_00"))
        view.addSubview(bkv)
        
        view.addSubview(s_titleLabel)
        view.addSubview(s_tpView)
        view.addSubview(s_imgView)
        view.addSubview(s_imgViewBack)
        view.addSubview(s_imgViewBtn)
        view.addSubview(s_imgViewTitle)
        view.addSubview(s_mapView)
        view.addSubview(s_nameLabel)
        view.addSubview(s_nameTextView)
        view.addSubview(s_describe)
        view.addSubview(s_describeTextView)
        view.addSubview(s_cancel)
        view.addSubview(s_sendNew)
        
        s_nameTextView.delegate   = self
        s_describeTextView.delegate = self
        
        s_immagePickerController.delegate = self
        s_immagePickerController.allowsEditing = true
        s_cancel.addTarget(self, action: #selector(self.cancelDidClick), forControlEvents: .TouchUpInside)
        s_sendNew.addTarget(self, action: #selector(self.sendNewDidClick), forControlEvents: .TouchUpInside)
        s_imgView.userInteractionEnabled = true
        s_imgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.presentAlert)))
        
        let s_lrMag = 20.0
        s_titleLabel.snp_makeConstraints { (make) in
            make.left.equalTo(self.view).offset(s_lrMag)
            make.top.equalTo(self.view).offset(7)
        }
        
        s_tpView.snp_makeConstraints { (make) in
            make.top.equalTo(self.view).offset(30.5)
            make.left.equalTo(self.view).offset(30)
            make.right.equalTo(self.view).offset(-30)
            make.height.equalTo(1)
        }
        
        s_imgViewBack.snp_makeConstraints { (make) in
            make.top.equalTo(s_tpView).offset(24)
            make.left.equalTo(s_lrMag)
            make.size.equalTo(CGSize(width: 173, height: 129.5))
            //w 346 h 259
        }
        
        s_imgView.snp_makeConstraints { (make) in
            make.top.left.equalTo(s_imgViewBack).offset(2)
            make.bottom.right.equalTo(s_imgViewBack).offset(-2)
        }
        
        s_imgViewBtn.snp_makeConstraints { (make) in
            make.left.equalTo(s_imgView.snp_right).offset(7.5)
            make.bottom.equalTo(s_imgView)
        }
        
        s_mapView.snp_makeConstraints { (make) in
            make.top.equalTo(s_imgView.snp_bottom).offset(35)
            make.left.equalTo(self.view).offset(s_lrMag)
            make.right.equalTo(self.view).offset(-s_lrMag)
            make.height.equalTo(90)
        }
        
        s_nameLabel.snp_makeConstraints { (make) in
            make.left.equalTo(self.view).offset(s_lrMag)
            make.top.equalTo(s_mapView.snp_bottom).offset(5)
        }
        
        s_nameTextView.snp_makeConstraints { (make) in
            make.left.equalTo(s_nameLabel)
            make.right.equalTo(self.view).offset(-s_lrMag)
            make.top.equalTo(s_mapView.snp_bottom).offset(25)
            make.height.equalTo(40)
        }
        
        s_describe.snp_makeConstraints { (make) in
            make.left.equalTo(s_nameTextView)
            make.top.equalTo(s_nameTextView.snp_bottom).offset(5)
        }
        
        s_describeTextView.snp_makeConstraints { (make) in
            make.top.equalTo(s_describe.snp_bottom).offset(5)
            make.left.equalTo(s_describe)
            make.right.equalTo(self.view).offset(-s_lrMag)
            make.height.equalTo(60)
        }
        
        s_cancel.snp_makeConstraints { (make) in
            make.top.equalTo(s_describeTextView.snp_bottom).offset(25)
            make.left.equalTo(self.view).offset(35)
        }
        
        s_sendNew.snp_makeConstraints { (make) in
            make.top.equalTo(s_cancel)
            make.right.equalTo(self.view).offset(-35)
        }
        
    }
}
